import { defineStore } from "pinia";
import { setItem, getItem } from "@/utils/localStorage";
import { setToken, getToken } from "@/utils/auth";
import { Alert, unAlert } from "@/utils/tool";

const useUserStore = defineStore("userStore", {
  state: () => {
    return {
      // 登录状态（是否登录） 默认：未登录(false)   登录true
      loginStatus: getItem("loginStatus") || false,
      // token令牌
      token: getToken() || "",
      // 同意协议（默认不同意，需要用户同意）(未同意不得登录)
      agree: false,
      userInfo: getItem("userInfo") || {},
      //***********用户设备的一些信息******** */
      //导航栏高度
      navHeight: "",
    };
  },
  actions: {
    // 修改登录状态
    updateLoginStatus(status: boolean) {
      this.loginStatus = status;
    },
    // 更新导航栏高度
    updateNavHeight() {
      const that = this;
      let menuButtonObject = wx.getMenuButtonBoundingClientRect();

      wx.getSystemInfo({
        success: (res) => {
          //导航高度
          let statusBarHeight_ = res.statusBarHeight;
          let navHeight_ =
            statusBarHeight_ +
            menuButtonObject.height +
            (menuButtonObject.top - statusBarHeight_) * 2;

          that.navHeight = String(navHeight_ + "px"); //导航栏总体高度

          // console.log("updateNavHeight：获取成功", navHeight_);
        },
        fail(err) {
          console.log(err);
        },
      });
    },
    // 更新用户信息
    updateUserInfo(data) {
      Alert("登录成功", "success", 500, true);

      this.userInfo = data;
      this.token = data.token;

      setItem("userInfo", data);
      setItem("token", data.token);

      setTimeout(() => {
        // 跳转到首页（逻辑在updateUserInfo里）
        uni.switchTab({ url: "/pages/index/index" });

        unAlert();
      }, 500);
    },
  },
  getters: {},
});

export default useUserStore;
